<template>
  <div id="app">
    <top-navigation 
      v-model="searchKeyword"
      @search="handleSearch"
      @fetch-suggestions="querySearch"
    />
    <el-container class="forum-container">
      <el-aside width="300px">
        <!-- 左侧功能区 -->
        <div class="left-section">
          <el-menu
            :default-active="activeMenu"
            class="el-menu-vertical-demo"
            @select="handleMenuSelect"
          >
            <el-menu-item index="diseaseForum">
              <i class="el-icon-s-home"></i>{{ diseaseName }}论坛
            </el-menu-item>
            <el-menu-item index="myPosts">
              <i class="el-icon-edit"></i>我的发表
            </el-menu-item>
            <el-menu-item index="myCollections">
              <i class="el-icon-star-on"></i>我的收藏
            </el-menu-item>
            <el-menu-item index="diseaseEncyclopedia">
              <i class="el-icon-info"></i>疾病百科
            </el-menu-item>
            <el-menu-item index="forumNavigation" @click="navigateToForum">
              <i class="el-icon-arrow-left"></i>返回论坛导航
            </el-menu-item>
          </el-menu>
          <div class="interaction-and-post">
            <el-button size="small" class="custom-badge">
              获赞 <span v-if="unreadLikes > 0" class="badge-count">{{ unreadLikes }}</span>
            </el-button>
            <el-button size="small" class="custom-badge">
              回复 <span v-if="unreadReplies > 0" class="badge-count">{{ unreadReplies }}</span>
            </el-button>
            <el-button 
              type="primary" 
              style="margin-left: 10px; width: auto; min-width: 100px;" 
              @click="openPostDialog"
            >
              我要发帖
            </el-button>
          </div>
        </div>
      </el-aside>

      <el-main>
        <div class="disease-header">
          {{ diseaseName }}论坛
        </div>
        <div class="filter-controls">
            <el-checkbox v-model="showStickyOnly">只看置顶帖</el-checkbox>
            <el-checkbox v-model="showEssenceOnly">只看精华帖</el-checkbox>
          </div>
        <!-- 右侧筛选和排序 -->
        <div class="right-section" v-if="activeMenu!== 'myPosts' && activeMenu!== 'myCollections'">
          <div class="filters">
            <div class="filter-group">
              <span>类别：</span>
              <el-radio-group v-model="category">
                <el-radio-button label="全部">全部</el-radio-button>
                <el-radio-button label="经验分享">经验分享</el-radio-button>
                <el-radio-button label="情感交流">情感交流</el-radio-button>
                <el-radio-button label="病情求助">病情求助</el-radio-button>
              </el-radio-group>
            </div>
            <div class="filter-group">
              <span>排序：</span>
              <el-radio-group v-model="sort">
                <el-radio-button label="最新">最新</el-radio-button>
                <el-radio-button label="最多评论">最多评论</el-radio-button>
                <el-radio-button label="最多点赞">最多点赞</el-radio-button>
              </el-radio-group>
            </div>
          </div>

          <!-- 帖子列表 -->
          <PostItem
            v-for="(post, index) in filteredPosts"
            :key="index"
            :post="post"
            :is-admin="isAdmin"
            @toggle-sticky="toggleSticky"
            @toggle-essence="toggleEssence"
            @like-post="likePost"
            @toggle-comment-input="toggleCommentInput"
            @collect-post="collectPost"
            @submit-comment="submitComment"
            @like-reply="likeReply"
            @submit-reply="handleReply"
            @delete-post="deletePost"
            @edit-post="editPost"
          />
        </div>
        <!-- 我的发表记录 -->
        <div class="right-section" v-else-if="activeMenu === 'myPosts'">
          <MyPosts />
        </div>
        <!-- 我的收藏 -->
        <div class="right-section" v-else-if="activeMenu === 'myCollections'">
          <MyCollections />
        </div>
      </el-main>
    </el-container>
    <!-- 引入发帖表单组件 -->
    <PublishPostDialog
      :showDialog="showDialog"
      :is-edit="!!currentEditedPost"
      :edited-post="currentEditedPost"
      @update:showDialog="showDialog = $event"  
      :newPostData="newPost"
      :uploadedFilesData="uploadedFiles"
      @file-change="handleFileChange"
      @remove-file="handleRemove"
      @preview-file="handlePictureCardPreview"
      @download-file="handleDownload"
      @submit-post="submitPost"
      @update-post="updatePost"
    />
  </div>
</template>

<script>
import PostItem from './PostItem.vue';
import '../assets/css/Forum.css';
import { Message } from 'element-ui';
import '../assets/css/DiseaseForum.css';
import diseaseForumData from '../assets/data/DiseaseForumData.js';
import PublishPostDialog from './PublishPostDialog.vue';
import TopNavigation from '@/components/TopNavigation.vue'
import api from '@/api/api';
import MyPosts from './MyPosts.vue';
import MyCollections from './MyCollections.vue'; 
export default {
  inject: ['reload'],
  components: {
    PostItem,
    PublishPostDialog,
    TopNavigation,
    MyPosts,
    MyCollections,
  },
  name: 'DiseaseForum',
  data() {
    return {
      localPosts: {}, // 初始化为空对象
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,
      uploadedFiles: [],
      commentReplies: [],
      diseaseName: this.$route.params.diseaseName,
      diseaseData:{},
      activeMenu: 'diseaseForum',
      collectedPosts: [],
      unreadLikes: 0,
      unreadReplies: 0,
      category: '全部',
      sort: '最新',
      newPost: {
        title: '',
        content: '',
        category: '经验分享'
      },
      myPostedPosts: [],
      diseaseEncyclopedia: '',
      searchKeyword: '',
      showDialog: false,
      diseaseEncyclopediaUrl: '',
      currentEditedPost: null,
      localPosts: { ...diseaseForumData.posts },
      isAdmin: true,
      showStickyOnly: false,
      showEssenceOnly: false,
      unreadLikes: 0, 
    unreadReplies: 0, 
    commentCounts: {}, // 用于存储每篇帖子的评论数
      likeCounts: {},
    };
  },
  computed: {
    filteredPosts() {
    let result = this.posts;
    console.log('原始帖子列表:', result); // 检查原始帖子列表

    // 置顶筛选
    if (this.showStickyOnly) {
      result = result.filter(post => post.isSticky);
      console.log('筛选后的置顶帖子:', result); // 检查筛选后的帖子
    }

    // 精华筛选
    if (this.showEssenceOnly) {
      result = result.filter(post => post.isEssence);
      console.log('筛选后的精华帖子:', result); // 检查筛选后的帖子
    }

    // 置顶排序（置顶帖在前）
    result = result.sort((a, b) => {
      if (a.isSticky !== b.isSticky) {
        return a.isSticky ? -1 : 1;
      }
      return new Date(b.date) - new Date(a.date);
    });

    // 类别筛选
    if (this.category !== '全部') {
      result = result.filter(post => post.category === this.category);
      console.log('筛选后的类别帖子:', result); // 检查筛选后的帖子
    }

    // 排序
    switch(this.sort) {
      case '最多评论':
        result.sort((a, b) => b.replies - a.replies);
        break;
      case '最多点赞':
        result.sort((a, b) => b.likes - a.likes);
        break;
      default:
        result.sort((a, b) => new Date(b.date) - new Date(a.date));
    }
    console.log('最终筛选排序后的帖子列表:', result); // 检查最终帖子列表
    return result;
  },
  posts() {
    return this.localPosts[this.diseaseName] || [];
  }
  },
  watch: {
    '$route'(to) {
      this.diseaseName = to.params.diseaseName;
      this.loadDiseaseData(this.diseaseName);
      this.collectedPosts = []; 
      this.generateEncyclopediaUrl(); 
      this.calculateInitialUnreads(); 
    }
  },
  created() {
  this.loadDiseaseData(this.diseaseName);
  this.loadPosts(); // 加载帖子数据
  this.generateEncyclopediaUrl();
  this.calculateInitialUnreads();
  this.fetchMyPostsData(); // 获取我的帖子数据

  },

  methods: {
    fetchMyPostsData() {
    api.getMyPosts()
      .then(response => {
        this.myPostedPosts = response.data;
        this.initializeLikeAndCommentCounts();
      })
      .catch(error => {
        console.error('获取我的帖子失败:', error);
        this.$message.error('获取我的帖子失败，请稍后再试');
      });
  },
  initializeLikeAndCommentCounts() {
    this.myPostedPosts.forEach(post => {
      this.$set(this.likeCounts, post.id, post.likes);
    });

    const commentCountPromises = this.myPostedPosts.map(post => {
      return api.getCommentCount(post.id)
        .then(response => {
          return { postId: post.id, count: response.data };
        });
    });

    Promise.all(commentCountPromises)
      .then(results => {
        results.forEach(result => {
          this.$set(this.commentCounts, result.postId, result.count);
        });
        this.calculateUnreadReplies();
      })
      .catch(error => {
        console.error('获取评论数失败:', error);
      });

    this.calculateUnreadLikes();
  },
    fetchLikeCounts() {
      api.getMyPosts()
        .then(response => {
          this.myPostedPosts = response.data;
          this.calculateUnreadLikes();
        })
        .catch(error => {
          console.error('获取我的帖子失败:', error);
          this.$message.error('获取我的帖子失败，请稍后再试');
        });
    },
    fetchCommentCounts() {
      api.getMyPosts()
        .then(response => {
          this.myPostedPosts = response.data;
          const commentCountPromises = this.myPostedPosts.map(post => {
            return api.getCommentCount(post.id)
              .then(response => {
                return { postId: post.id, count: response.data };
              });
          });

          Promise.all(commentCountPromises)
            .then(results => {
              results.forEach(result => {
                if (result.postId) {
                  this.$set(this.commentCounts, result.postId, result.count);
                }
              });
              this.calculateUnreadReplies();
            })
            .catch(error => {
              console.error('获取评论数失败:', error);
            });
        })
        .catch(error => {
          console.error('获取我的帖子失败:', error);
          this.$message.error('获取我的帖子失败，请稍后再试');
        });
    },

    calculateUnreadLikes() {
    this.unreadLikes = this.myPostedPosts.reduce((sum, post) => sum + post.likes, 0);
  },

  // 计算总评论数
  calculateUnreadReplies() {
    this.unreadReplies = Object.values(this.commentCounts).reduce((sum, count) => sum + count, 0);
  },
    
  
 
  async likePost(postId) {
    try {
      await api.likePost(postId);
      const response = await api.getPostById(postId);
      const postIndex = this.myPostedPosts.findIndex(post => post.id === postId);
      if (postIndex !== -1) {
        this.myPostedPosts[postIndex].likes = response.data.likes;
        this.$set(this.likeCounts, postId, response.data.likes);
      }
      this.calculateUnreadLikes();
      this.$message.success('点赞成功');
    } catch (error) {
      console.error('点赞失败:', error);
      this.$message.error('点赞失败，请稍后再试');
    }
  },
async submitComment(postId, commentData) {
    try {
      await api.createComment(postId, commentData);
      const response = await api.getCommentCount(postId);
      this.$set(this.commentCounts, postId, response.data);
      this.calculateUnreadReplies();
      this.$message.success('评论提交成功');
    } catch (error) {
      console.error('评论提交失败:', error);
      this.$message.error('评论提交失败，请稍后再试');
    }
  },


    getFullImageUrl(relativePath) {
    return `${process.env.VUE_APP_API_BASE_URL}/uploads/${relativePath}`; // 根据你的实际情况调整
  },
    loadDiseaseData(diseaseName) {
      console.log(`加载 ${diseaseName} 数据...`);
      if (diseaseForumData.diseaseEncyclopedias && 
          diseaseForumData.diseaseEncyclopedias[diseaseName]) {
        this.diseaseEncyclopedia = diseaseForumData.diseaseEncyclopedias[diseaseName];
      } else {
        this.diseaseEncyclopedia = '暂无该疾病百科信息';
      }
    },
    submitReply({ post, parentReply, content }) {
      const newReply = {
        user: {
          avatar: require('@/assets/images/Avatar1.png'),
          nickname: '当前用户昵称'
        },
        content: content,
        date: new Date().toISOString(),
        likes: 0,
        replies: []
      };

      if (parentReply) {
        if (!parentReply.replies) {
          this.$set(parentReply, 'replies', []);
        }
        parentReply.replies.push(newReply);
      } else {
        post.comments.push(newReply);
      }

      post.replies++;
      if (post.user.nickname === '当前用户昵称') {
        this.unreadReplies++;
      }
      this.$forceUpdate();
    },

    submitSubReply({ post, parentReply, content }) {
      const newSubReply = {
        user: {
          avatar: require('@/assets/images/Avatar1.png'),
          nickname: '当前用户昵称'
        },
        content: content,
        date: new Date().toISOString(),
        likes: 0
      };

      if (!parentReply.replies) {
        this.$set(parentReply, 'replies', []);
      }
      parentReply.replies.push(newSubReply);
      post.replies++;
      this.$forceUpdate();
    },
    // 置顶/取消置顶
    toggleSticky(post) {
      post.isSticky = !post.isSticky;
      this.$message.success(post.isSticky ? '帖子已置顶' : '已取消置顶');
    },
    
    // 设置/取消精华
    toggleEssence(post) {
      post.isEssence = !post.isEssence;
      this.$message.success(post.isEssence ? '设为精华帖' : '已取消精华');
    },
    // 生成百度百科链接
    generateEncyclopediaUrl() {
  this.diseaseEncyclopediaUrl = `https://baike.baidu.com/item/${encodeURIComponent(this.diseaseName)}`;
},
    handleMenuSelect(key) {
      this.activeMenu = key;
      if (key === 'diseaseEncyclopedia') {
        window.open(this.diseaseEncyclopediaUrl, '_blank'); // 打开百度百科链接
      }
    },
    navigateToForum() {
      this.$router.push({ name: 'Forum' }); 
    },
    collectPost(post) {
      const index = this.collectedPosts.findIndex(p => p.id === post.id);
      if (index === -1) {
        this.collectedPosts.push({ ...post, isCollected: true });
        post.isCollected = true;
        this.$message.success('收藏成功');
      } else {
        this.collectedPosts.splice(index, 1);
        post.isCollected = false;
        this.$message.success('已取消收藏');
      }
    },
    removeCollection(post) {
      this.collectedPosts = this.collectedPosts.filter(p => p.id !== post.id);
      post.isCollected = false;
      this.$message.success('已移除收藏');
    },
    calculateInitialUnreads() {
      this.unreadLikes = this.posts
        .filter(post => post.user.nickname === '当前用户昵称')
        .reduce((sum, post) => sum + post.likes, 0);

      this.unreadReplies = this.posts
        .filter(post => post.user.nickname === '当前用户昵称')
        .reduce((sum, post) => sum + post.replies, 0);
    },
    likePost(post) {
      post.likes++;
      if (post.user.nickname === '当前用户昵称') {
        this.unreadLikes++;
      }
    },
    toggleCommentInput(post) {
      post.showCommentInput = !post.showCommentInput;
    },
    submitComment(post) {
      if (post.newComment) {
        const newComment = {
          user: {
            avatar: require('@/assets/images/Avatar1.png'),
            nickname: '当前用户昵称'
          },
          content: post.newComment,
          date: new Date().toISOString(),
          likes: 0,
          replies: []
        };
        post.comments.push(newComment);
        post.replies++;
        if (post.user.nickname === '当前用户昵称') {
          this.unreadReplies++;
        }
        post.newComment = '';
        post.showCommentInput = false;
      } else {
        this.$message.error('评论内容不能为空');
      }
    },
    likeComment(comment) {
      comment.likes++;
      this.unreadLikes++;
    },
    toggleReplyInput(comment) {
      this.$set(comment, 'showReplyInput', !comment.showReplyInput);
      this.$forceUpdate();
    },
    handleReply({ post, parentReply, content }) {
      const newReply = {
        user: {
          avatar: require('@/assets/images/Avatar1.png'),
          nickname: '当前用户昵称'
        },
        content: content,
        date: new Date().toISOString(),
        likes: 0,
        replies: []
      };

      if (parentReply) {
        if (!parentReply.replies) {
          this.$set(parentReply, 'replies', []);
        }
        parentReply.replies.push(newReply);
      } else {
        post.comments.push(newReply);
      }

      post.replies++;
      if (post.user.nickname === '当前用户昵称') {
        this.unreadReplies++;
      }
      this.$forceUpdate();
    },
    likeReply(reply) {
      reply.likes++;
      this.unreadLikes++;
    },
    toggleSubReplyInput(reply) {
      if (!reply.hasOwnProperty('newSubReply')) {
        this.$set(reply, 'newSubReply', '');
      }
      this.$set(reply, 'showSubReplyInput', !reply.showSubReplyInput);
    },
    handleSearch() {
      console.log('搜索关键词：', this.searchKeyword);
    },

    querySearch(queryString, cb) {
      const results = queryString
       ? this.posts.filter(post => 
          post.title.includes(queryString) || post.content.includes(queryString)
        )
        : this.posts;
      cb(results);
    },

    openPostDialog() {
      this.showDialog = true;
      this.currentEditedPost = null; 
      this.newPost = {
        title: '',
        content: '',
        category: '经验分享'
      };
      this.uploadedFiles = [];
    },

    closePostDialog() {
      this.showDialog = false;
      this.currentEditedPost = null;
    },

    handleFileChange(file, fileList) {
      this.uploadedFiles = fileList;
    },

    handleRemove(file, fileList) {
      this.uploadedFiles = fileList;
    },

    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },

    handleDownload(file) {
      console.log('下载文件：', file);
    },

    async submitPost(newPostData) {
    if (!newPostData.title.trim()) {
      this.$message.error('标题不能为空');
      return;
    }
    if (newPostData.content.trim().length < 10) {
      this.$message.error('内容长度不能少于10个字');
      return;
    }

    try {
      const files = this.uploadedFiles.map(file => file.raw);
      const response = await api.createPost(newPostData, files);
      if (!this.localPosts[this.diseaseName]) {
        this.$set(this.localPosts, this.diseaseName, []); 
      }
      this.localPosts[this.diseaseName].unshift(response.data);
      this.myPostedPosts.unshift(response.data);
      this.closePostDialog();
      this.newPost = { title: '', content: '', category: '经验分享' };
      this.uploadedFiles = [];
      this.$message.success('发帖成功');
    } catch (error) {
      console.error('发帖失败:', error);
      this.$message.error('发帖失败，请稍后再试');
    }
  },
  async deletePost(post) {
  try {
    await api.deletePost(post.id);

    // 更新 localPosts
    if (this.localPosts[this.diseaseName]) {
      this.localPosts[this.diseaseName] = this.localPosts[this.diseaseName].filter(p => p.id !== post.id);
    }

    // 更新 myPostedPosts
    this.myPostedPosts = this.myPostedPosts.filter(p => p.id !== post.id);

    // 更新 collectedPosts
    this.collectedPosts = this.collectedPosts.filter(p => p.id !== post.id);

    // 重新计算未读点赞和回复数
    this.calculateUnreadLikes();
    this.calculateUnreadReplies();

    this.$message.success('帖子删除成功');
    await this.loadPosts();
    window.location.reload();
  } catch (error) {
    console.error('删除帖子失败:', error);
    this.$message.error('删除帖子失败，请稍后再试');
  }
},

editPost(post) {
    this.currentEditedPost = { ...post }; 
    this.showDialog = true; 
    this.newPost = {
      title: post.title,
      content: post.content,
      category: post.category
    };
    this.uploadedFiles = post.images || [];
  },

  async updatePost(updatedPost) {
  try {
    const formData = new FormData();
    if (updatedPost.title !== undefined) formData.append('title', updatedPost.title);
    if (updatedPost.content !== undefined) formData.append('content', updatedPost.content);
    if (updatedPost.category !== undefined) formData.append('category', updatedPost.category);
    if (updatedPost.likes !== undefined) formData.append('likes', updatedPost.likes);
    if (updatedPost.replies !== undefined) formData.append('replies', updatedPost.replies);
    if (updatedPost.isSticky !== undefined) formData.append('isSticky', updatedPost.isSticky);
    if (updatedPost.isEssence !== undefined) formData.append('isEssence', updatedPost.isEssence);
    if (this.uploadedFiles && this.uploadedFiles.length > 0) {
      this.uploadedFiles.forEach((file, index) => {
        formData.append(`files[${index}]`, file);
      });
    }

    const response = await api.updatePost(updatedPost.id, formData);
    if (response.data) {
      this.localPosts[this.diseaseName] = this.localPosts[this.diseaseName].map(p =>
        p.id === updatedPost.id ? response.data : p
      );
      this.myPostedPosts = this.myPostedPosts.map(p =>
        p.id === updatedPost.id ? response.data : p
      );
      this.collectedPosts = this.collectedPosts.map(p =>
        p.id === updatedPost.id ? response.data : p
      );
      this.$message.success('帖子更新成功');
      this.closePostDialog();
    }
  } catch (error) {
    console.error('更新帖子失败:', error);
    this.$message.error('更新帖子失败，请稍后再试');
  }
},
    
    async loadPosts() {
    try {
      const response = await api.getAllPosts();
      console.log('从后端获取到的帖子数据:', response.data); // 检查后端返回的数据
      // 确保 localPosts 中有当前疾病名的键
      if (!this.localPosts[this.diseaseName]) {
        this.$set(this.localPosts, this.diseaseName, []); // 初始化为空数组
      }
      this.localPosts[this.diseaseName] = response.data;
    } catch (error) {
      console.error('获取帖子失败:', error);
      this.$message.error('获取帖子失败，请稍后再试');
    }
  },
  async fetchPosts() {
      try {
        const response = await api.getAllPosts();
        if (!this.localPosts[this.diseaseName]) {
      this.$set(this.localPosts, this.diseaseName, []); // 确保有该键
    }
    this.localPosts[this.diseaseName] = response.data;
    response.data.forEach(post => {
      this.getCommentCount(post.id);
    });
  } catch (error) {
        console.error('获取帖子列表失败:', error);
      }
    },
    async submitComment(postId, commentData) {
    try {
      await api.createComment(postId, commentData);
      const response = await api.getCommentCount(postId);
      this.$set(this.commentCounts, postId, response.data);
      this.calculateUnreadReplies();
      this.$message.success('评论提交成功');
    } catch (error) {
      console.error('评论提交失败:', error);
      this.$message.error('评论提交失败，请稍后再试');
    }
  },

    async getComments(postId) {
      try {
        const response = await api.getComments(postId);
        if (this.localPosts[this.diseaseName]) {
      const post = this.localPosts[this.diseaseName].find(p => p.id === postId);
      if (post) {
        post.comments = response.data;
      }
    }
  }  catch (error) {
        console.error('获取评论失败:', error);
      }
    },
    async getCommentCount(postId) {
      try {
        const response = await api.getCommentCount(postId);
        if (this.localPosts[this.diseaseName]) {
      const post = this.localPosts[this.diseaseName].find(p => p.id === postId);
      if (post) {
        post.replies = response.data;
      }
    }
  }catch (error) {
        console.error('获取评论数量失败:', error);
      }
    },


},
mounted() {
    this.fetchPosts();
  },
  beforeRouteEnter(to, from, next) {
    next(vm => {
      vm.fetchPosts();
    });
  },

    
  }

</script>    